package sdk.webview.fmc.com.fmcsdk.app;

import android.app.Activity;

import java.util.Stack;

import sdk.webview.fmc.com.fmcsdk.util.GsonUtil;
import sdk.webview.fmc.com.fmcsdk.util.KLog;

/**
 * 应用程序Activity管理类：用于Activity管理和应用程序退出
 */
public class AppManager {

    private static Stack<Activity> activityStack;
    private static AppManager instance;
    //被系统回收缓存的activity
    private static Stack<String> cacheStack;
    private AppManager(){
        activityStack=new Stack<Activity>();
        cacheStack = new Stack<String>();
    }
    /**
     * 单一实例
     */
    public static AppManager getAppManager(){
        if(instance==null){
            instance=new AppManager();
        }
        return instance;
    }
    /**
     * 添加Activity到堆栈
     */
    public void addActivity(Activity activity){
        if(activityStack==null){
            activityStack=new Stack<Activity>();
        }
        activityStack.add(activity);
    }

    /**
     * 添加被系统回收的activity到堆栈缓存，当activity回到前台再移除
     * @param activity 需要缓存的activity
     */
    public void addCacheActivity(Activity activity){
        if(cacheStack==null){
            cacheStack=new Stack<String>();
        }
        String name = activity.getClass().getName();
        if (!cacheStack.contains(name)){
            cacheStack.add(name);
        }
    }

    public void removeCacheActivity(Activity activity){
        String name = activity.getClass().getName();
        if (cacheStack != null && cacheStack.contains(name)){
            cacheStack.remove(name);
        }
    }
    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    public Activity currentActivity(){
        Activity activity=activityStack.lastElement();
        return activity;
    }
    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    public void finishActivity(){
        Activity activity=activityStack.lastElement();
        finishActivity(activity);
    }
    /**
     * 结束指定的Activity
     */
    public void finishActivity(Activity activity){
        if(activity!=null){
            activityStack.remove(activity);
            activity.finish();
            activity=null;
        }
    }
    /**
     * 结束指定类名的Activity
     */
    public void finishActivity(Class<?> cls){
        try {
            for (Activity activity : activityStack) {
                if(activity.getClass().equals(cls) ){
                    finishActivity(activity);
                }
            }
        }catch (Exception e){

        }
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity(){
        for (int i = 0, size = activityStack.size(); i < size; i++){
            if (null != activityStack.get(i)){
                activityStack.get(i).finish();
            }
        }
        activityStack.clear();
        if (cacheStack != null)
            cacheStack.clear();

    }
    /**
     * 退出应用程序
     */
    public void appExit( ) {
        try {
            finishAllActivity();
            System.exit(0);
        } catch (Exception e) {	}
    }



    /**
     * 获取界面数量
     *
     * @return activity size
     */
    public  int getActivitySize() {
        if (activityStack != null) {
            return activityStack.size();
        }
        return 0;
    }

    /**
     * 判断一个Activity 是否存在
     *
     * @param clz
     * @return
     */

    public static  boolean isActivityExist(Class<?> clz) {
        if (activityStack==null){
            return false;
        }
        boolean res  = false;
        for (int i = 0; i < activityStack.size(); i++) {
            Activity activity = activityStack.get(i);
            if ( activity.getClass().equals(clz)) {
                if (activity.isFinishing() || activity.isDestroyed()) {
                    res = false;
                } else {
                    res = true;
                }
            }
        }
        return res;
    }

    public static Activity getTopActivity() {
        Activity mBaseActivity = null;
        synchronized (activityStack) {
            final int size = activityStack.size() - 1;
            if (size < 0) {
                return null;
            }
            mBaseActivity = activityStack.get(size);
        }
        return mBaseActivity;

    }

    public void setH5Activity(Class<?> clz,Activity activity){
        if(isActivityExistFinish(clz)){
            activityStack.set(0,activity);
        }
    }
    public static  boolean isActivityExistFinish(Class<?> clz) {
        if (activityStack==null){
            return false;
        }
        boolean res  = false;
        for (int i = 0; i < activityStack.size(); i++) {
            Activity activity = activityStack.get(i);
            if ( activity.getClass().equals(clz)) {
                if (activity.isFinishing() || activity.isDestroyed()) {
                    res = false;
                } else {
                    res = true;
                    activityStack.remove(i);
                }
            }
        }
        return res;
    }


    /**
     * 将指定的Activity移动到栈顶
     * @param activity 要移动到栈顶的Activity实例
     */
    public void moveActivityToTop(Activity activity) {
        if (activity != null && activityStack != null && activityStack.contains(activity)) {
            // 先从栈中移除该Activity
            activityStack.remove(activity);
            // 然后将其添加到栈顶
            activityStack.add(activity);
        }
    }

    /**
     * 通过类名将指定类型的Activity移动到栈顶
     * @param cls 要移动到栈顶的Activity类
     */
    public void moveActivityToTop(Class<?> cls) {
        if (cls == null || activityStack == null) return;
        for (int i = 0; i < activityStack.size(); i++) {
            Activity activity = activityStack.get(i);
            if (activity.getClass().equals(cls)) {
                // 移除并重新添加到栈顶
                activityStack.remove(i);
                activityStack.add(activity);
                break;
            }
        }
    }
    /**
     * 将指定的Activity移动到栈底
     * @param activity 要移动到栈底的Activity实例
     */
    public void moveActivityToBottom(Activity activity) {
        if (activity != null && activityStack != null && activityStack.contains(activity)) {
            // 先从栈中移除该Activity
            activityStack.remove(activity);
            // 然后将其添加到栈底
            activityStack.insertElementAt(activity, 0); // 注意：Stack类不直接支持此操作，需要转换为Vector或ArrayList来使用
        }
    }

    /**
     * 通过类名将指定类型的Activity移动到栈底
     * @param cls 要移动到栈底的Activity类
     */
    public void moveActivityToBottom(Class<?> cls) {
        if (cls == null || activityStack == null) return;
        for (int i = activityStack.size() - 1; i >= 0; i--) { // 从栈顶开始遍历，避免在遍历时修改集合导致的问题
            Activity activity = activityStack.get(i);
            if (activity.getClass().equals(cls)) {
                // 移除并重新添加到栈底
                activityStack.remove(i);
                activityStack.add(0, activity); // 使用add(0, element)将元素插入到列表的开头
                break;
            }
        }

        for (int i=0;i<activityStack.size();i++){
            KLog.e(activityStack.get(i).toString());
        }


    }
}